﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace NSpotifyLib
{
    internal class TrackReader : BaseReader<Track>
    {
        internal TrackReader(XDocument document) : base(document)
        {
        }

        public override IEnumerable<Track> Read()
        {
           var tracks = from track in document.Descendants(ns + SpotifyTags.Track)
                        select new Track
                        {
                            SpotifyLink = track.Attribute(SpotifyTags.SpotifyLink).Value,
                            Name = track.Element(ns + SpotifyTags.Name).Value,
                            Artist = (from artist in track.Descendants(ns + SpotifyTags.Artist)
                                      select new Artist
                                      {
                                          Name = artist.Element(ns + SpotifyTags.Name).Value,
                                          SpotifyLink = artist.Attribute(SpotifyTags.SpotifyLink) != null ? artist.Attribute("href").Value : String.Empty
                                      }).FirstOrDefault(),
                            
                            Album = (from album in track.Descendants(ns + SpotifyTags.Album)
                                     select new Album
                                     {
                                         Name =  album.Element(ns + SpotifyTags.Name).Value,
                                         SpotifyLink = album.Attribute(SpotifyTags.SpotifyLink) != null ? album.Attribute("href").Value : String.Empty,
                                         Released = album.Element(ns + SpotifyTags.Released) != null ? Int32.Parse(album.Element(ns + SpotifyTags.Released).Value) : 0
                                     }).FirstOrDefault(),

                            TrackNumber = Int32.Parse(track.Element(ns + SpotifyTags.TrackNumber).Value),
                           
                            Length = Double.Parse(track.Element(ns +SpotifyTags.Length).Value),

                            Popularity = Double.Parse(track.Element(ns + SpotifyTags.Popularity).Value)
                        };

           return tracks;
        }
    }
}
